<template>
	<view class="x-main-content">
		<view class="bgimg"
			style="background-image: url('https://peiyiwang.obs.cn-east-3.myhuaweicloud.com:443/file%2F5337842972788471.png')">
			<image class="left" src="../../static/icon/left_back.png" @click="leftClick()"></image>
		</view>
		<view class="form_content">
			<view style="padding: 30rpx;">
				<view class="bt">
					<image src="../../static/home/bt5.png" mode=""></image>
					<text class="btn-txt">您现在正在办理[{{detailObj.name}}]下单服务，请如实填写信息</text>
					<text class="des" v-show="detailObj.introduction != null">{{detailObj.introduction}}</text>
				</view>
				<u-form :model="form" :rules="rules" ref="uForm" :label-style="labelStyle" errorType="toast">
					<u-form-item label="价格(元)" borderBottom>
						<u-input v-model="detailObj.price" disabled placeholderClass="plaClass"
								 disabledColor="#ffffff" border="none"></u-input>
					</u-form-item>
					<u-form-item @click="goChooseHospital()" label="购买地址" prop="hospital" borderBottom>
						<u-input v-model="form.hospital" disabled placeholderClass="plaClass" disabledColor="#ffffff"
							placeholder="选择购买的医院" border="none"></u-input>
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>
					<u-form-item @click="goPatients()" label="请选择就诊人" prop="patients" borderBottom>
						<u-input v-model="form.patients" disabled placeholderClass="plaClass" disabledColor="#ffffff"
							placeholder="选择就诊人" border="none"></u-input>
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>
					<u-form-item label="药品类型" prop="serviceType" borderBottom>
						<u-radio-group v-model="form.serviceType" placement="row" @change="groupChange">
							<u-radio v-for="(item, index) in lists" :key="index" :label="item.name" :name="item.name"
								@change="radioChange">
							</u-radio>
						</u-radio-group>
					</u-form-item>
					<!-- 	<view class="line">
						<u-form-item label="处方照片" prop="appointmentDate"  @click="dateShow=true">
							<u-input v-model="form.appointmentDate" disabled placeholderClass="plaClass"
								disabledColor="#ffffff" placeholder="注:处方药需要上传处方" border="none"></u-input>
							<u-icon slot="right" name="arrow-right"></u-icon>
						</u-form-item>
						<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
							:maxCount="10"></u-upload>
					</view> -->

					<u-form-item label="请选择服务时间" prop="appointmentDate" borderBottom @click="dateShow=true">
						<u-input v-model="form.appointmentDate" disabled placeholderClass="plaClass"
							disabledColor="#ffffff" placeholder="选择服务时间" border="none"></u-input>
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>
					<!-- <u-form-item label="送往地址" prop="appointmentDate" borderBottom @click="dateShow=true">
						<u-input v-model="form.appointmentDate" disabled placeholderClass="plaClass"
							disabledColor="#ffffff" placeholder="选择地址" border="none"></u-input>
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item> -->
					<u-form-item label="送去地址" prop="address" borderBottom>
						<u-input v-model="form.address" placeholderClass="plaClass"
							disabledColor="#ffffff" placeholder="请填写送去地址" border="none"></u-input>
					</u-form-item>
					<u-form-item class="sepclial" label="特殊需求(选填)" prop="specifyInfo">
						<u-textarea v-model="form.specifyInfo" placeholder="请填写您的特殊需求" confirmType="done"
							placeholderStyle="font-size: 28rpx;font-family: PingFangSC-Light, PingFang SC;font-weight: 300;color: #6F7DA2;letter-spacing: 1px;">
						</u-textarea>
					</u-form-item>
				</u-form>
				<view class="btn-box" style="padding: 0 20rpx;margin-top: 60rpx;">
					<view class="btn">
						<u-button text="下单" :hairline="false" :customStyle="commonBtnStyle" color="#386FFF"
							@click="goBuy"></u-button>
					</view>
				</view>
			</view>
		</view>
		<u-datetime-picker ref="datetimePicker" :show="dateShow" mode="datetime" v-model="timeOptions.value"
			:minDate="timeOptions.min" :maxDate="timeOptions.max" :formatter="formatter" @cancel="dateCancel"
			@confirm="dateConfirm">
		</u-datetime-picker>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				fileList1: [],
				form: {
					hospital: "", //医院
					appointmentDate: "", // 时间
					specifyInfo: "", // 特殊需求
					patients: "", //就诊人
					administrativeOffice: "", //科室
					serviceType: "" ,// 服务类型
					address:'',
				},
				detailObj:{},
				lists: [{
						name: '处方',
						disabled: false
					},
					{
						name: '非处方',
						disabled: false
					}
				],
				dateShow: false,
				radiovalue1: '专家',
				timeOptions: {
					value: 0,
					max: 0,
					min: 0
				},
				labelStyle: {
					color: '#333',
					fontSize: '14px',
					textAlign: 'left',
					fontWeight: '400',
					letterSpacing: '1px',
					fontFamily: 'PingFangSC - Regular,PingFang SC'
				},
				rules: {
					hospital: [{
						require: true,
						message: '请选择医院',
						trigger: ['blur', 'change']
					}],
					patients: [{
						require: true,
						message: '请选择就诊人',
						trigger: ['blur', 'change']
					}],
					administrativeOffice: [{
						require: true,
						message: '请选择科室',
						trigger: ['blur', 'change']
					}],
					appointmentDate: [{
						require: true,
						message: '请选择时间',
						trigger: ['blur', 'change']
					}],
					serviceType: [{
						require: true,
						message: '请选择服务类型',
						trigger: ['blur', 'change']
					}]

				}
			}
		},
		onShow() {
		},
		onLoad(option) {
			let openId = uni.getStorageSync('openId')
			if(openId){
				this.openId = openId
			}
			this.index = option.search
			this.timeOptions.value = Number(new Date())
			// 预计+14天
			this.timeOptions.max = new Date('2100-01-01').getTime()
			this.timeOptions.min = Number(new Date())
			
			// 获取当前页面实例
			const pages = getCurrentPages();
			const currentPage = pages[pages.length - 1];
			// 获取页面链接携带的参数
			var urlParams = currentPage.options;
			console.log(urlParams)
			console.log("查看参数"+urlParams.id)
			this.getDetail(urlParams.id)
			uni.$on('hospital',this.resHospitall)
			uni.$on('patients',(patientSelection)=>{
				this.form.patients = patientSelection.name
				this.form.contactPhone = patientSelection.phone
				this.form.idCardNumber = patientSelection.idCard
			})
		},
		methods: {
			resHospitall(hospital1) {
				if(this.form.hospital != hospital1.name){
					this.form.departmentId = ''
					this.form.departmentName = ''
					this.form.doctorId = ''
					this.form.doctorName = ''
				}
				this.form.hospital = hospital1.name
				this.form.hospitalId = hospital1.id
			},
			leftClick() {
				uni.navigateBack({
					delta: 1
				});
			},
			goChooseHospital() {
				this.$u.route({
					url: 'pages/business/components/chooseHospitals'
				})
			},
			goPatients() {
				this.$u.route({
					url: 'pages/business/components/patients'
				})
			},
			groupChange(n) {
				console.log('groupChange', n);
			},
			radioChange(n) {
				console.log('radioChange', n);
			},
			dateConfirm(e) {
				// console.log('value', e)
				// this.params.appointmentDate = e[0]
				this.form.appointmentDate = uni.$u.timeFormat(e.value, 'yyyy-mm-dd hh:MM')
				this.dateCancel()
			},
			dateCancel() {
				this.dateShow = false
			},
			formatter(type, value) {
				// console.log('type', type)
				if (type === 'year') {
					return `${value}年`
				}
				if (type === 'month') {
					return `${value}月`
				}
				if (type === 'day') {
					return `${value}日`
				}
				if (type === 'hour') {
					return `${value}时`
				}
				if (type === 'minute') {
					return `${value}分`
				}
				return value
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.search, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: 'http://192.168.2.21:7001/upload', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						formData: {
							user: 'test'
						},
						success: (res) => {
							setTimeout(() => {
								resolve(res.data.data)
							}, 1000)
						}
					});
				})
			},
			async getDetail(id){
				let data = {}
				let res = await this.$request(`/api/service/detail/${id}`, data, 'GET')
				console.log('res',res)
				this.$nextTick(()=>{
					this.detailObj = res.data.data
				})
			},
			async getOpenId() {
				if (!this.openId) {
					let getId = await this.uniLogin()
					return getId
				}
				return this.openId
			},
			async uniLogin() {
				let code = await this.getcode()
				return this.getIdByCode(code)
			},
			async getcode() {
				return new Promise((resolve, reject) => {
					uni.login({
						provider: 'weixin',
						success: res => {
							resolve(res.code)
						}
					})
				})
			},
			async getIdByCode(code){
				let phoneNumber = uni.getStorageSync('userInfo').phonenumber
				let params = {
					code: code,
					phoneNumber
				}
				let resId = await this.$request('/api/applet/getOpenId', params, 'get').then(res=>{
					let openId = res.data.data.openid
					uni.setStorageSync('openId',openId)
					this.openId = openId
					return openId
				}).catch(err=>{
					uni.hideLoading()
					return this.openId
				})
				return resId
			},
			async goBuy() {
				// this.$refs.uForm.validate().then(() => {
				// 	console.log(222222)
				// })
				if(!this.form.hospital){
					this.$u.toast('请选择医院')
					return
				}
				if(!this.form.patients){
					this.$u.toast('请选择就诊人')
					return
				}
				if(!this.form.serviceType){
					this.$u.toast('请选择类型')
					return
				}
				if(!this.form.appointmentDate){
					this.$u.toast('请选择服务时间')
					return
				}
				let _this = this
				let params = {
					// "acceptUserId": 0,
					// "address": "",
					"amount": _this.detailObj.price,
					"appointmentDate": _this.form.appointmentDate,
					"buyType": 1,
					"contactName": _this.form.patients,
					"contactPhone": _this.form.contactPhone,
					// "drugType": "",
					"hospitalId": _this.form.hospitalId,
					"idCardNumber": _this.form.idCardNumber,
					"num": 1,
					"productId": _this.detailObj.id,
					"registrationType": _this.form.administrativeOffice,
					"specialNeeds": _this.form.specifyInfo
				}
				let res = await this.$request('/api/serviceOrder/submitServiceOrder', params, 'POST','type')
				console.log("res",res)
				if(res.data.code == 200){
					this.recharge(res.data.data)
				}
			},
			async recharge(res){
				uni.showLoading({
					title: "请求中..."
				})
				let _this = this
				// res.data.data.amount.serviceOrderSn
				let openId = await this.getOpenId()
				let params ={
					"isCustomize": "0",
					"openId": openId,
					"orderNum": res.serviceOrderSn,
					"payType": "WX_APPLET_PAY",
					"paymentAmount": res.amount,
					"rechargeAmount": 0,
				}
				let resVal = await this.$request('/api/userAccount/recharge', params, 'POST','type')
				console.log('resVal',resVal)
				uni.hideLoading();
				if(resVal.data.code == 200){
					let resData = resVal.data.data
					wx.requestPayment({
						timeStamp: resData.timeStamp,
						nonceStr: resData.nonceStr,
						package: 'prepay_id=' + resData.prepay_id,
						signType: 'MD5',
						paySign: resData.paySign,
						success (res) {
							_this.$u.route({
								url: '/packageA/pages/order/order',
								params: {
									label: 3,
									back:2
								}
							})
						},
						fail (res) {
							console.log('failres',res)
						}
					})
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.bgimg {
		width: 100%;
		height: 180px;
		position: absolute;
		// box-sizing: border-box;
		background-size: 100%;
		background-repeat: no-repeat;

		.left {
			width: 8px;
			height: 16px;
			margin-left: 50rpx;
			margin-top: 78rpx;
		}

	}

	.form_content {
		position: absolute;
		margin-top: 150px;
		margin-left: 20rpx;
		margin-right: 20rpx;
		width: calc(100vw - 20px);
		// height: calc(100vh - 180px);
		height: 100vh;
		background: #ffffff;
		border-radius: 30rpx 30rpx 0 0;

		.bt {
			padding: 0 20rpx;
			display: flex;
			flex-direction: column;
			border-bottom: 1px solid rgb(214, 215, 217);

			image {
				width: 115rpx;
				height: 50rpx;
			}

			.btn-txt {
				font-size: 26rpx;
				font-family: PingFangSC-Light, PingFang SC;
				font-weight: 300;
				color: #777777;
				letter-spacing: 1px;
				margin-top: 8rpx;
				margin-bottom: 44rpx;
			}
		}
	}

	.line {
		border-bottom: 1px solid rgb(214, 215, 217);

		/deep/.u-upload {
			padding: 0 20rpx;
		}

		/deep/.u-upload__button {
			border-radius: 20rpx;
		}
	}

	.plaClass {
		text-align: right;
		font-size: 28rpx;
		font-family: PingFangSC-Light, PingFang SC;
		font-weight: 300;
		color: #6F7DA2;
		letter-spacing: 1px;
		margin-right: 10px;
	}

	/deep/ .u-form-item__body__left {
		width: 20vh !important;
		margin-left: 10px;
	}

	/deep/.u-form-item__body {
		padding: 15px 0 !important;
	}

	/deep/.item__body__right__content__icon {
		margin-left: 10rpx;
	}

	/deep/.u-radio-group--row {
		justify-content: space-around;
	}

	.sepclial {
		/deep/.u-form-item__body {
			flex-direction: column !important;
		}

		/deep/.u-form-item__body__right__content {
			margin-top: 15px !important;
			padding: 0 9px !important;
		}

		.u-textarea {
			background: #F4F6FA;
			border-radius: 20rpx;
		}

		.u-border {
			border-style: none
		}
	}
</style>